<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/4/28
 * Time: 9:52
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Age extends Base
{
    public function index(){
        if(Request::instance()->isAjax()){
            //生日
            $birthday = Db::table('up_u_user')
                ->column('user_birthday');
            $age_arr = [];//接收年龄数组
            $byear = date('Y');
            $birthday1 = array_filter($birthday);
            //根据生日，循环计算年龄
            foreach($birthday1 as $k => $v){
                $time = date('Y', strtotime($v));//取得生日的时间戳
                $age = $byear - $time;
                array_push($age_arr, $age);
            }
            $age_arr = array_unique($age_arr);//去重之后的年龄数组
            sort($age_arr);//正序排序
            
            $list = [];
            $num = count($age_arr);
            if($num > 0){
                for($i = $age_arr[0]; $i <= $age_arr[$num-1]; $i++){
                    //如果$i在年龄数组中
                    if(in_array($i, $age_arr)){
                        $year = $byear - $i;
                        $where['user_birthday'] = ['like', '%' . $year . '%'];
                        $count = Db::table('up_u_user')->where($where)->count();
                        $a['name'] = $i;
                        $a['value'] = $count;
                        array_push($list, $a);
                    }
                }
            }
            return json(['age' => $list]);
        }
        return $this->fetch('age/index');
    }
}